<?php

require_once("functions.php");
$db = connect_db();

if (isset($argv[1]) && isset ($argv[2]) && isset($argv[3])) {
	$lang = $argv[1];
	$file = $argv[2];
	$def = $argv[3];
} else
	die ("Need parameters: <language> <file> <defines>");

define ('ORIGINAL_PAGE', 'URDD');


require_once($def);
require_once($file);

$lang = mysql_real_escape_string($lang);
$sql = "select id from languages  where language='$lang'";
$res = mysql_query($sql, $db);

if ($res == FALSE)
	die (mysql_error());
$row = mysql_fetch_array($res);
if ($row === FALSE)
	die ("Unknown language");
$lang = $row[0];

function insert_var($lang, $var, $evar, $val)
{
	global $db;
	
	$like_evar = ($evar !== NULL) ? "fields.extra_variable like '" . mysql_real_escape_string($evar) . "' and " : '';
	$var = mysql_real_escape_string($var);
	$evar = mysql_real_escape_string($evar);
	$sql = "select id from fields where $like_evar variable like '$var' limit 1";
	$res = mysql_query($sql, $db);
	if ($res == FALSE)
		die (mysql_error());
	$var_id = @mysql_result($res, 0,0);
	$val_id = FALSE;
	if($var_id !== FALSE) {
		$sql = "select id from `values` where variable_id='$var_id' and language_id='$lang' limit 1";
		echo $sql;
		$res = mysql_query($sql, $db);
		if ($res == FALSE)
			die (mysql_error());
		$val_id = @mysql_result($res, 0,0);
	} else {
		$sql = "insert into fields (variable, extra_variable) values ('$var', '$evar')";
		$res = mysql_query($sql, $db);
		$var_id = mysql_insert_id($db);
	}
	if (is_array($val)) {
		$v = mysql_real_escape_string($val[0]);
		$v2 = mysql_real_escape_string($val[1]);
	} else {
		$v = $v = mysql_real_escape_string($val);
		$v2 = NULL;
	}
	if ($val_id !== FALSE) {
		$sql = "update `values` set language_id=$lang, variable_id=$var_id, value='$v', value2='$v2' where id=$val_id";
	} else {
		$sql = "insert into `values` (language_id, variable_id, value, value2) values ($lang, $var_id, '$v', '$v2')";
	}
	$res = mysql_query($sql, $db);
	echo "insert: $var, $evar : $val\n";

}


foreach($LN as $var=>$val) {
	if (is_array($val)) {
		foreach($val as $evar=>$val2)
			insert_var($lang, $var, $evar, $val2);
	} else
		insert_var($lang, $var, NULL, $val);
}



?>
